package com.arch.flink.archetype.sinkdemo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * @author pizhihui
 * @date 2023-08-03 15:19
 */
public class RichSinkFunctionDemo1 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);

        DataStreamSource<Student> source = env.fromElements(new Student(1, "站三", 18));

        source.addSink(new StudentSink());

        env.execute("test sink demo1");

    }

    public static class StudentSink extends RichSinkFunction<Student> {

        PreparedStatement ps;
        Connection connection;

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);

            connection = DriverManager.getConnection("jdbc:mysql://node1:3306/bigdata", "root", "123456");
            String sql = "insert into t_student(id, name, age) values(?,?,?)";
            ps = connection.prepareStatement(sql);

            RuntimeContext runtimeContext = getRuntimeContext();
            String taskName = runtimeContext.getTaskName();
            System.out.println(taskName);

        }


        @Override
        public void invoke(Student value, Context context) throws Exception {
            ps.setInt(1, value.getId());
            ps.setString(2, value.getName());
            ps.setInt(3, value.getAge());
            ps.execute();
        }

        @Override
        public void close() throws Exception {
            if (ps != null) {
                ps.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }


    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Student {
        private Integer id;
        private String name;
        private Integer age;
    }

}
